<template>
  <div class="docstatu">
    <div class="search">
      <el-button
        type="primary"
        @click="docAddupdate(0)"
        plain="plain"
        class="addDoc"
        size="small"
      >添加文档</el-button>
    </div>
    <base-table ref="baseTable" :tableSetting="tableSetting" @handleCommon="handleCommon"></base-table>
    <!-- 添加文档弹框 -->
    <el-dialog
      :title="titleStation"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="dialogStation"
      width="500px"
      center
    >
      <el-form
        status-icon
        ref="form"
        :model="form"
        label-width="120px"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="name">
          <el-input v-model.trim="form.name" maxlength="32" placeholder="请输入文档标题"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="tabType">
          <el-select v-model="form.tabType" placeholder="请选择">
            <el-option v-for="item in tabPane" :key="item.id" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文档" prop="path">
          <el-upload
            :headers="headers"
            class="upload-demo"
            :action="uploading"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
          >
            <el-button size="small" type="primary" plain="plain">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close('form')">取 消</el-button>
        <el-button type="primary" @click="save('form')" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import baseTable from "@/components/table/baseTable";
import menuleft from "@/components/menuItem/menuleft.vue";
import {
  documentList,
  documentsevenList,
  documenteightList,
  documentfivesList,
  addDocument,
  addDocumentseven,
  addDocumenteight,
  addDocumentfives,
  updateDocument,
  deleteDocument,
  downloadFile,
  stickDoc,
  selectDocument,
} from "@/service/Api.js"; //接口

import { mapGetters } from "vuex";

import typeArr from "@/utils/typeArr";

export default {
  components: { baseTable, menuleft },
  name: "documentMent",
  props: ["menuFlag", "tabPane"],
  data() {
    return {
      tableSetting: {
        tableApiFn: documentList,
        defaulteParams: {
          docParentId: "1",
        },
        placed: {
          label: "是否置顶",
          handleName: "handleSwitch",
        },
        options_type: [],
        options: [
          { prop: "name", label: "标题" },
          { prop: "userName", label: "上传者" },
          { prop: "createTime", label: "上传时间" },
        ],
        btns: [
          { text: "下载", size: "mini", handleName: "handleExport" },
          {
            text: "编辑",
            size: "mini",
            handleName: "docAddupdate",
            type: "primary",
            plain: "plain",
          },
          {
            text: "删除",
            size: "mini",
            handleName: "handDelete",
            type: "danger",
            plain: "plain",
          },
        ],
      },
      keyword: "",
      dialogStation: false,
      titleStation: "",
      loading: false,
      fileList: [],
      pn: 1,
      ps: 10,
      type: "",
      form: {
        name: "",
        path: "",
        tabType: "",
      },
      rules: {
        name: [{ required: true, message: "请输入文档标题", trigger: "blur" }],
        path: [{ required: true, message: "请选择文档", trigger: "blur" }],
        tabType: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      static: "",
      id: "",
      uploading: "api/upload/uploadFile/6",
      headers: {
        "API-User-Token": sessionStorage.getItem("token"), //文件上传需携带token
      },
      fileTypeArr: typeArr,
    };
  },
  computed: {
    ...mapGetters(["documentType", "docParentId"]),
  },
  watch: {
    documentType(newVlaue, oldValue) {
      this.tableSetting.defaulteParams = {
        documentType: newVlaue === "first" ? "" : newVlaue,
      };
      this.$refs.baseTable.initData();
    },
    docParentId(newValue, oldValue) {
      this.$store.commit("SET_DOCUMENT_TYPE", "");
      this.$refs.baseTable.initData(
        {
          docParentId: newValue,
        },
        true
      );
    },
    menuFlag(val) {
      // if (val == "10") {
      //   this.tableSetting.tableApiFn=documentList;
      //   this.uploading="api/upload/uploadFile/6";
      // } else if (val == "12") {
      //    this.tableSetting.tableApiFn=documentsevenList;
      //   this.uploading="api/upload/uploadFile/7";
      // } else if (val == "13") {
      //    this.tableSetting.tableApiFn=documenteightList;
      //   this.uploading="api/upload/uploadFile/8";
      // } else {
      //    this.tableSetting.tableApiFn=documentfivesList;
      //    this.uploading="api/upload/uploadFile/5";
      // }
      // setTimeout(() => {
      //   this.$refs.baseTable.initData();
      // }, 10);
    },
  },
  methods: {
    handleCommon(name, row, idx) {
      if (this[name]) {
        this[name](row, idx);
      }
    },
    handleSwitch(row) {
      stickDoc(row.id).then((res) => {
        this.$message.success("操作成功");
        this.$refs.baseTable.initData();
      });
    },
    //下载
    handleExport(row) {
      this.$confirm("此操作将下载文档, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then((res) => {
        fetch(row.path).then(async (res) => {
          let data = await res.blob();
          var link = document.createElement("a");

          var body = document.querySelector("body");

          link.href = window.URL.createObjectURL(data);
          let arr = this.fileTypeArr.filter((el) => {
            if (row.path.indexOf(el) !== -1) {
              return el;
            }
          });
          if (arr.length > 0) {
            if (arr.length > 1) {
              link.download = row.name + arr[1];
            } else {
              link.download = row.name + arr[0];
            }
            link.style.display = "none";
            body.appendChild(link);
            link.click();
            body.removeChild(link);
            window.URL.revokeObjectURL(link.href);
          }
        });

      });
    },
    //上传格式及大小
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "jpg";
      const extension2 = testmsg === "png";
      const extension3 = testmsg === "pdf";
      const extension4 = testmsg === "doc";
      const extension5 = testmsg === "xls";
      const extension6 = testmsg === "ppt";
      const extension7 = testmsg === "xlsx";
      const extension8 = testmsg === "docx";
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if(!extension && !extension2 && !extension3 && !extension4 && !extension5 && !extension6 && !extension7 && !extension8) {
      //     this.$message({
      //         message: '上传文件只能是 jpg、png、pdf、doc、xls、ppt、docx、xlsx、格式!',
      //         type: 'warning'
      //     });
      // }
      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning",
          offset: "500px",
        });
      }
      return true;
    },
    handleAvatarSuccess(res, file) {
      this.form.name = file.name.split(".")[0];
      this.imageUrl = URL.createObjectURL(file.raw);
      if (res.code == 0) {
        console.log("xiangying", res);
        this.form.path = res.data.fileIds;
      } else {
        this.$message.error(res.message);
      }
    },
    //文档管理-添加/删除/修改
    docAddupdate(row) {
      this.dialogStation = true;
      this.$nextTick(() => {
        if (row == 0) {
          this.titleStation = "添加文档";
          this.static = 0;
          this.id = "";
          this.form.name = "";
          this.form.path = "";
          this.form.tabType = Number(this.documentType) || "";
        } else {
          this.titleStation = "文档修改";
          this.static = 2;
          this.id = row.id;
          this.form.name = row.name;
          this.uid = row.uid;
          this.form.path = row.path;
          this.form.tabType = row.type;
          this.getDocument(row.id);
        }
      });
    },
    getDocument(id) {
      selectDocument(id).then((response) => {
        if (response.code === 0) {
          this.form.name = response.data.name;
          this.fileList.push({
            name: response.data.name,
            url: response.data.documentType,
          });
        }
      });
    },
    //删除
    handDelete(row) {
      this.$confirm("此操作将永久删除,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteDocument(row.id, row.uid).then((res) => {
            if (res.code == 0) {
              this.$message.success("删除成功!");
              this.$refs.baseTable.initData();
            } else {
              this.$message.warning(res.message);
            }
          });
        })
        .catch(() => {});
    },
    //关闭弹框
    close(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
        this.fileList = [];
      });
      this.dialogStation = false;
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          let data = {
            id: this.id,
            name: this.form.name,
            path: this.form.path,
            uid: this.uid,
            type: this.form.tabType,
          };
          if (this.static == 0) {
            this.menuFlag == "11"
              ? (url = addDocument(data))
              : this.menuFlag == "12"
              ? (url = addDocumentseven(data))
              : this.menuFlag == "13"
              ? (url = addDocumenteight(data))
              : (url = addDocumentfives(data));
          } else {
            url = updateDocument(data);
          }
          url.then((res) => {
            this.fileList = [];
            if (res.code == 0) {
              this.$message.success("操作成功!");
              this.close("form");
              this.$refs.baseTable.initData();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }

        this.uid = "";
      });
    },
  },
};
</script>
<style scoped>
.addDoc {
  margin-bottom: 15px;
}
</style>
